package com.qianfeng.es.service.impl;

//
//                            _ooOoo_  
//                           o8888888o  
//                           88" . "88  
//                           (| -_- |)  
//                            O\ = /O  
//                        ____/`---'\____  
//                      .   ' \\| |// `.  
//                       / \\||| : |||// \  
//                     / _||||| -:- |||||- \  
//                       | | \\\ - /// | |  
//                     | \_| ''\---/'' | |  
//                      \ .-\__ `-` ___/-. /  
//                   ___`. .' /--.--\ `. . __  
//                ."" '< `.___\_<|>_/___.' >'"".  
//               | | : `- \`.;`\ _ /`;.`/ - ` : | |  
//                 \ \ `-. \_ __\ /__ _/ .-` / /  
//         ======`-.____`-.___\_____/___.-`____.-'======  
//                            `=---='  
//  
//         .............................................  
//                  佛祖镇楼                  BUG辟易  
//          佛曰:  
//                  写字楼里写字间，写字间里程序员；  
//                  程序人员写程序，又拿程序换酒钱。  
//                  酒醒只在网上坐，酒醉还来网下眠；  
//                  酒醉酒醒日复日，网上网下年复年。  
//                  但愿老死电脑间，不愿鞠躬老板前；  
//                  奔驰宝马贵者趣，公交自行程序员。  
//                  别人笑我忒疯癫，我笑自己命太贱；  
//  


import com.fasterxml.jackson.databind.ObjectMapper;
import com.qianfeng.es.service.QueryService;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.action.search.SearchScrollRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.text.Text;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.reindex.BulkByScrollResponse;
import org.elasticsearch.index.reindex.DeleteByQueryRequest;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * Created by Jackiechan on 2022/6/29 21:27
 *
 * @author Jackiechan
 * @version 1.0
 * @since 1.0
 */
@Service
public class QueryServiceImpl implements QueryService {


    private ObjectMapper objectMapper;


    @Autowired
    public void setObjectMapper(ObjectMapper objectMapper) {
        this.objectMapper = objectMapper;
    }

    private RestHighLevelClient restHighLevelClient;

    @Autowired
    public void setRestHighLevelClient(RestHighLevelClient restHighLevelClient) {
        this.restHighLevelClient = restHighLevelClient;
    }

    @Override
    public void termQuery(String index, String feild, String value) throws Exception {
//        //创建请求
//        SearchRequest searchRequest = new SearchRequest(index);
//        //创建一个查询条件的构建者
//        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
//        //设置查询条件
//        searchSourceBuilder.query(QueryBuilders.termQuery(feild,value));
//        searchRequest.source(searchSourceBuilder);
//        //查询数据
//        SearchResponse response = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);
        SearchResponse response = baseQuery(index, QueryBuilders.termQuery(feild, value));
        //遍历获取数据
        Arrays.stream(response.getHits().getHits()).forEach(searchHit->System.err.println(searchHit.getSourceAsString()));
    }

    @Override
    public void termsQuery(String index, String feild, String... values) throws Exception {
//        //创建请求
//        SearchRequest searchRequest = new SearchRequest(index);
//        //创建一个查询条件的构建者
//        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
//        //设置查询条件
//        searchSourceBuilder.query(QueryBuilders.termsQuery(feild,values));
//        searchRequest.source(searchSourceBuilder);
//        //查询数据
//        SearchResponse response = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);
        SearchResponse response = baseQuery(index, QueryBuilders.termsQuery(feild, values));
        //遍历获取数据
        Arrays.stream(response.getHits().getHits()).forEach(searchHit->System.err.println(searchHit.getSourceAsString()));
    }

    @Override
    public void matchAll(String index) throws Exception {
        SearchResponse response = baseQuery(index, QueryBuilders.matchAllQuery());
        Arrays.stream(response.getHits().getHits()).forEach(searchHit->System.err.println(searchHit.getSourceAsString()));
    }

    @Override
    public void matchQuery(String index, String feild, String value) throws Exception {
        SearchResponse response = baseQuery(index, QueryBuilders.matchQuery(feild,value));
        Arrays.stream(response.getHits().getHits()).forEach(searchHit -> System.err.println(searchHit.getSourceAsString()));
    }

    @Override
    public SearchResponse createScrollQuery(String index, QueryBuilder queryBuilder, int size) throws Exception {
        //创建请求
        SearchRequest searchRequest = new SearchRequest(index);
        //设置为滚动的深分页查询
        searchRequest.scroll("1m");
        //创建一个查询条件的构建者
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        //设置查询条件
        searchSourceBuilder.query(queryBuilder);
        //设置期望的数量
        searchSourceBuilder.size(size);
        searchRequest.source(searchSourceBuilder);

        //查询数据
        SearchResponse response = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);
        //遍历获取数据
        Arrays.stream(response.getHits().getHits()).forEach(searchHit -> System.err.println(searchHit.getSourceAsString()));
        return response;
    }

    @Override
    public SearchResponse scrollQuery(String scrollId) throws Exception {

        //创建滚动查询,设置上次的id
        SearchScrollRequest scrollRequest = new SearchScrollRequest(scrollId).scroll("1m");
        //查询
        SearchResponse response = restHighLevelClient.scroll(scrollRequest, RequestOptions.DEFAULT);
        Arrays.stream(response.getHits().getHits()).forEach(searchHit -> System.err.println(searchHit.getSourceAsString()));

        return response;
    }

    @Override
    public void deleteByQuery(String index, QueryBuilder queryBuilder) throws Exception {
        DeleteByQueryRequest deleteByQueryRequest = new DeleteByQueryRequest(index).setQuery(queryBuilder);
        BulkByScrollResponse response = restHighLevelClient.deleteByQuery(deleteByQueryRequest, RequestOptions.DEFAULT);
        System.err.println(objectMapper.writeValueAsString(response));
    }

    @Override
    public void boolQuery(String index, QueryBuilder queryBuilder) throws Exception {
        SearchResponse response = baseQuery(index, queryBuilder);
        Arrays.stream(response.getHits().getHits()).forEach(searchHit -> System.err.println(searchHit.getSourceAsString()));
    }

    @Override
    public void boostingQuery(String index, QueryBuilder boostingQueryBuild) throws Exception {
        SearchResponse response = baseQuery(index, boostingQueryBuild);
        Arrays.stream(response.getHits().getHits()).forEach(searchHit -> System.err.println(searchHit.getSourceAsString()));
    }

    @Override
    public void highLightQuery(String index, QueryBuilder queryBuilder, String preTag, String postTag, String... highLightField) throws Exception {
        //创建请求
        SearchRequest searchRequest = new SearchRequest(index);

        //创建一个查询条件的构建者
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        //设置高亮的条件
        HighlightBuilder highlightBuilder = new HighlightBuilder();
        highlightBuilder.fragmentSize(0)//返回所有数据
                .preTags(preTag)
                .postTags(postTag);
        if (highLightField != null) {
            //遍历设置高亮的字段
            Arrays.stream(highLightField).forEach(highLight->{
                highlightBuilder.field(highLight);
            });
        }

        searchSourceBuilder.highlighter(highlightBuilder);
        //设置查询条件
        searchSourceBuilder.query(queryBuilder);
        searchRequest.source(searchSourceBuilder);
        //查询数据
        SearchResponse response = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);
        //遍历获取数据
//        Arrays.stream(response.getHits().getHits()).forEach(searchHit -> {
//            try {
//                System.err.println(searchHit.getSourceAsString()+"---->"+objectMapper.writeValueAsString(searchHit.getHighlightFields()));
//            } catch (JsonProcessingException e) {
//                throw new RuntimeException(e);
//            }
//        });
        List<Map<String, Object>> result = Arrays.stream(response.getHits().getHits()).map(searchHit -> {
            //获取原始数据
            Map<String, Object> sourceAsMap = searchHit.getSourceAsMap();
            //获取高亮的数据
            Map<String, HighlightField> highlightFields = searchHit.getHighlightFields();
            //遍历所有的高亮字段
            highlightFields.entrySet().forEach(entry -> {
                //拿到每一个高亮的数据
                String key = entry.getKey();//高亮的字段
                HighlightField value = entry.getValue();//高亮的内容
                if (value != null) {
                    //获取所有的高亮的片段
                    Text[] fragments = value.fragments();
                    if (fragments != null) {
                        //对应的高亮内容
                        String hlValue = fragments[0].toString();
                        //将原始的数据替换成高亮
                        sourceAsMap.put(key, hlValue);
                    }
                }
            });
            //返回每一条数据
            return sourceAsMap;
        }).collect(Collectors.toList());

        System.err.println(result);
    }

    /**
     * 封装的查询方法
     * @param index 查询的库
     * @param queryBuilder 查询条件
     * @return
     * @throws IOException
     */
    public SearchResponse baseQuery(String index, QueryBuilder queryBuilder) throws IOException {
        //创建请求
        SearchRequest searchRequest = new SearchRequest(index);
        //创建一个查询条件的构建者
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        //设置查询条件
        searchSourceBuilder.query(queryBuilder);
        searchRequest.source(searchSourceBuilder);
        //查询数据
        SearchResponse response = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);
        //遍历获取数据
        return response;
    }


}
